import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:pp_page/pp_page_controller.dart';

// ignore: must_be_immutable
abstract class PPWidget<T extends PPPageController> extends GetView<T> {
  PPWidget({Key? key}) : super(key: key);

  @override
  // ignore: overridden_fields
  final String tag =
      "${T.toString()}-${DateTime.now()}-${Random().nextInt(16)}";

  @override
  T get controller {
    var cusTag = bindControllerTag();
    return GetInstance().find<T>(tag: cusTag ?? tag);
  }

  bool _isInitController = false;

  @override
  Widget build(BuildContext context) {
    if (!_isInitController) {
      _isInitController = true;
      var cusTag = bindControllerTag();
      Get.put<T>(bindController(context), tag: cusTag ?? tag);
    }
    return GestureDetector(
      onPanDown: (details) {
        _hideKeyboard(context);
      },
      onTap: () {
        _hideKeyboard(context);
      },
      child: buildBody(context),
    );
  }

  T bindController(BuildContext context);

  String? bindControllerTag() {
    return null;
  }

  Widget buildBody(BuildContext context);

  /// 收键盘
  void _hideKeyboard(BuildContext context) {
    SystemChannels.textInput.invokeMethod('TextInput.hide');
  }
}
